package com.sduept.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Calendar;
import java.util.Date;

public class TimeTool {
    private static Logger logger = LoggerFactory.getLogger(TimeTool.class);

    public static byte[] getCp56Time2a(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int ms = calendar.get(Calendar.SECOND) * 1000 + calendar.get(Calendar.MILLISECOND);
        byte[] rel = new byte[7];
        rel[0] = (byte)(ms & 0x00FF);
        rel[1] = (byte)((ms >> 8) & 0x00FF);;
        rel[2] = (byte)calendar.get(Calendar.MINUTE);
        rel[3] = (byte)calendar.get(Calendar.HOUR_OF_DAY);
        rel[4] = (byte)calendar.get(Calendar.DAY_OF_MONTH);
        rel[5] = (byte)(calendar.get(Calendar.MONTH) + 1);
        rel[6] = (byte)(calendar.get(Calendar.YEAR) % 100);
        return rel;
    }

    public static Date getDateByCp56(byte[] cp56) {
        int ms = cp56[1] & 0x00FF;
        ms = ms << 8;
        ms |= (cp56[0] & 0x00FF);
        int minute = cp56[2] & 0x003F;
        int hour = cp56[3] & 0x001F;
        int day = cp56[4] & 0x001F;
        int month = cp56[5] & 0x000F;
        int year = cp56[6] & 0x007F;
        year += 2000;

        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(year, month - 1, day, hour, minute);
        long totalMs = calendar.getTimeInMillis() + ms;
        calendar.setTimeInMillis(totalMs);
        return calendar.getTime();
    }
}
